<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('action.import')"
    width="600px"
    class="dialogs"
  >
    <div style="padding: 8px 0; background: #f8fbff; margin-top: 10px">
      <div class="tip">
        <div class="bold">1</div>
        <span class="btitle">{{ t('formItems.downloadTemplate') }}</span>
      </div>
      <el-row :gutter="24">
        <div class="el-upload__tip text-center">
          <span>{{ t('formItems.importRequire') }}</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            {{ t('formItems.downloadImportTemplate') }}
          </el-link>
        </div>
      </el-row>
    </div>


    <div style="padding: 8px 0; background: #f8fbff; margin-top: 10px">
      <div class="tip">
        <div class="bold">2</div>
        <span class="btitle">{{ t('formItems.importFile') }}</span>
      </div>
      <el-row :gutter="24">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      style="text-align: center"
      class="upload-demo"
      :action="importUrl"
      drag
      :headers="uploadHeaders"
      :limit="1"
      :before-upload="beforeAvatarUpload"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      name="file"
    >
      <Icon icon="ep:upload" />
      <div style="padding: 8px 0 ; text-align: center;" class="el-upload__text">{{ t('formItems.uploadRequire') }}<em>{{ t('formItems.clickUpload') }}</em></div>
    </el-upload>
    </el-row>
    </div>



<!--    <div style="padding: 8px 0; background: #f8fbff; margin-top: 10px">
      <div class="tip">
        <div class="bold">3</div>
        <span class="btitle">删除</span>
      </div>
      <el-row :gutter="24">
        <el-input
          v-model="importBatch"
          placeholder="请输入批次号"
          clearable

          class="!w-240px"
        />
        <el-button  @click="handleDelete">按批次号删除导入数据</el-button>
      </el-row>
    </div>-->

    <template #footer>
      <el-button
        :disabled="formLoading"
        type="primary"
        @click="reportDepartment"
        >{{ t('action.import') }}</el-button
      >
      <el-button @click="dialogVisible = false">{{ t('action.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth';
import { DeviceBaseApi } from '@/api/base/devicebase'
import download from '@/utils/download';
defineOptions({ name: 'ObjectImportForm' });
const { t } = useI18n() // 国际化
const message = useMessage(); // 消息弹窗
const reportData = {
  fileUrl: null
};
const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中
const uploadRef = ref();
const importUrl =
  import.meta.env.VITE_BASE_URL +
  import.meta.env.VITE_API_URL +
  '/base/devicebase/uploadFile';
const uploadHeaders = ref(); // 上传 Header 头
const fileList = ref([]); // 文件列表

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true;
  fileList.value = [];
  resetForm();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/*const handleDelete = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    //发起删除
    if(importBatch.value != ''){
      await DeviceBaseApi.deleteLyntglAmmeterInfo2(importBatch.value)
    message.success(t('common.delSuccess'))
    emit('success');
 
  importBatch.value = ''
    }
    dialogVisible.value = false;
   
  } catch {}
}*/
// 判断文件格式
const beforeAvatarUpload = (file) => {
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  };
  const fileName = file.name;
  file.value = file.name;
  let flag = false;
  // 取出上传文件的扩展名
  const index = fileName.lastIndexOf('.');
  const ext = fileName.substring(index + 1);
  // 循环比较
  if (ext === 'xlsx' || ext === 'xls') {
    flag = true;
  }
  if (!flag) {
    message.error(t('formItems.uploadError1'));
    return false;
  }
  return true;
};
// 上传成功之后文件非空判断
const uploadSuccess = (response) => {
  if (response.code === 0) {
    reportData.fileUrl = response.data;
  } else {
    reportData.fileUrl = null;
    message.error(t('formItems.uploadError2'));
    return;
  }
};
//保存导入
/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const reportDepartment = async () => {
  if (!reportData.fileUrl) {
    message.error(t('formItems.uploadError3'));
    return;
  }
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  };
  formLoading.value = true;

  await DeviceBaseApi.reportDepartment(reportData)
    .then((res: any) => {
      message.success('上传成功');
      dialogVisible.value = false;
      emit('success');
    })
    .catch((res: any) => {
      DeviceBaseApi.downloadWrongReport(reportData).then((res: any) => {
        downloadByData(res, '导入模版错误信息.xlsx');
      });
    });
  formLoading.value = false;
};

/**
 * 拿到文件流后的下载的方法
 * @param {*} data
 * @param {*} filename
 * @param {*} mime
 * @param {*} bom
 */
const downloadByData = async (
  data: BlobPart,
  filename: string,
  mime?: string,
  bom?: BlobPart
) => {
  const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
  const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });

  const blobURL = window.URL.createObjectURL(blob);
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', filename);
  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank');
  }
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(blobURL);
};
/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！');
  formLoading.value = false;
};

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false;
  uploadRef.value?.clearFiles();
};

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！');
};

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await DeviceBaseApi.importTemplate();
  download.excel(res, '导入模版.xlsx');
};
</script>
<style scoped>

:deep(.el-form-item__label) {
  width: 130px !important;
}
.bold {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #85afd5;
  text-align: center;
  margin-top: 5px;
  margin-left: -10px;
  color: #fff;
}
.btitle {
  line-height: 30px;
  margin-left: 10px;
  color: #84b0d5;
}
.tip {
  border: 1px solid #84b0d5;
  border-radius: 0 20px 20px 0;
  width: 140px;
  height: 30px;
  display: flex;
  margin-left: 30px;
  margin-bottom: 20px;
}
</style>
